package com.wedu.modules.dss.controller;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.wedu.common.utils.PageUtils;
import com.wedu.common.utils.R;
import com.wedu.modules.dss.AjaxResult;
import com.wedu.modules.dss.CustomSheetWriteHandler;
import com.wedu.modules.dss.ExcelImportListener;
import com.wedu.modules.dss.MinioUtils;
import com.wedu.modules.dss.dao.DssDeviceInformationDao;
import com.wedu.modules.dss.dao.DssOperationStatusDao;
import com.wedu.modules.dss.entity.DssDeviceInformationEntity;
import com.wedu.modules.dss.entity.DssDeviceProductionEntity;
import com.wedu.modules.dss.entity.DssOperationStatusEntity;
import com.wedu.modules.dss.entity.OperationStatusEntity;
import com.wedu.modules.dss.entity.dto.DssDeviceInformationDTO;
import com.wedu.modules.dss.service.DssDeviceInformationService;
import com.wedu.modules.dss.service.DssFollowService;
import com.wedu.modules.dss.service.DssOperationStatusService;
import com.wedu.modules.dss.service.DssOperationStatusService1;
import com.wedu.modules.sys.controller.AbstractController;
import com.wedu.modules.sys.dao.SysDictDao;
import com.wedu.modules.sys.entity.SysDictEntity;
import io.minio.http.Method;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 主表，设备信息表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/dss/deviceInformation")
public class DssDeviceInformationController extends AbstractController {
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private DssDeviceInformationDao dssDeviceInformationDao;
    @Autowired
    private DssDeviceInformationService dssDeviceInformationService;

    @Autowired
    private DssFollowService dssFollowService;
    @Autowired
    private DssOperationStatusService dssOperationStatusService;
    @Autowired
    private SysDictDao sysDictDao;
    /**
     * 分页列表
     */
    @RequestMapping("list")
    @RequiresPermissions("dss:deviceInformation:list")
    public R list(@RequestParam Map<String,Object> params){

        Long userId = getUserId();//获取当前登录对象对象的Id
        PageUtils page=dssDeviceInformationService.queryPage(params,userId);

        return  R.ok().put("page", page);

    }
    /**
     * 查询字典列表数据
     */
    @GetMapping("/dict/list")
    @RequiresPermissions("dss:deviceInformation:list")
    public R childList() {
        Map<String, Object> dictMap = dssDeviceInformationService.queryChildPage();

        return R.ok().put("dictMap", dictMap);
    }

    /**
     * 按照id查询
     */
    @RequestMapping("info/{id}")
    @RequiresPermissions("dss:deviceInformation:info")
    public R info(@PathVariable("id") Long id){
        DssDeviceInformationEntity deviceInformation=dssDeviceInformationService.getById(id);

        return R.ok().put("deviceInformation",deviceInformation);

    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("dss:deviceInformation:save")
    public R save(@RequestBody DssDeviceInformationEntity deviceInformation){
        deviceInformation.setCreateTime(new Date());
       deviceInformation.setCreateBy(getUserId());
        dssDeviceInformationService.saveWarning(deviceInformation);

        OperationStatusEntity dssOperationStatus=new OperationStatusEntity();
        dssOperationStatus.setDeviceId(deviceInformation.getId());
        dssOperationStatus.setLightStatus(1);
        dssOperationStatus.setLightStartTime(deviceInformation.getStartUseTime());
        dssOperationStatusService.save(dssOperationStatus);



        return R.ok();

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("dss:deviceInformation:update")
    public R update(@RequestBody DssDeviceInformationEntity deviceInformation){
        deviceInformation.setUpdateTime(new Date());
        deviceInformation.setUpdateBy(getUserId());

        if (deviceInformation.getMaintenancePlan().equals("1")){
            Integer x = deviceInformation.getMaintenanceCycle();
            Integer y = deviceInformation.getAdvanceTime();
            Date date1 = new Date();
            Calendar calendar1 = Calendar.getInstance();
            calendar1.add(Calendar.DATE,x);/***/
            date1 = calendar1.getTime();
            deviceInformation.setMaintenanceDueTime(date1);
            Date date2 = new Date();
            Calendar calendar2 = Calendar.getInstance();
            calendar2.add(Calendar.DATE,(x-y));/***/
            date2 = calendar2.getTime();
            deviceInformation.setNoticeTime(date2);
        }else if (deviceInformation.getMaintenancePlan().equals("2")){
            Integer x = deviceInformation.getMaintenanceCycle();
            Date date1 = new Date();
            Calendar calendar1 = Calendar.getInstance();
            calendar1.add(Calendar.HOUR,x);/***/
            date1 = calendar1.getTime();
            deviceInformation.setMaintenanceDueTime(date1);
            deviceInformation.setNoticeTime(date1);
        }

        dssDeviceInformationService.updateById(deviceInformation);

        return R.ok();

    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("dss:deviceInformation:delete")
    public R delete(@RequestBody Long[] ids){
        dssDeviceInformationService.removeByIds(Arrays.asList(ids));
        dssFollowService.removeByIds(Arrays.asList(ids));
        return R.ok();

    }


    /**
     * 下载导出Excel文件
     * 注意,返回值是void
     */
    @GetMapping("export/excel")
    @RequiresPermissions("dss:deviceInformation:export")
    public void downloadExcel(@RequestParam Map<String,Object> params, HttpServletResponse response) throws IOException {

        //查询字典数据，用于模板下拉框
        QueryWrapper<SysDictEntity> dictQueryWrapper=new QueryWrapper<>();
        dictQueryWrapper.eq("code","deviceType").eq("type","2");
        List<SysDictEntity> dictData = sysDictDao.selectList(dictQueryWrapper);

        List<String> dictList=new ArrayList<>();
        for (SysDictEntity dictEntity : dictData) {
            dictList.add(dictEntity.getName());
        }




        //获取当前用户数据
        Long userId = getUserId();

        //设置 HTTP 响应头，触发浏览器下载Excel文件，并正确处理中文文件名
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");// 是 Office Open XML 标准 MIME 类型，声明响应内容为 Excel 文件
        String fileName = URLEncoder.encode("设备台账.xlsx", "UTF-8");//避免特殊字符（如中文、空格）导致 HTTP 头解析错误
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName);//attachment：强制浏览器以下载形式处理响应内容，Content-Disposition是HTTP响应头


        PageUtils page=dssDeviceInformationService.queryPage(params,userId);


//        String filepath="D:\\迅雷下载\\";
      //  String templateFileName =filepath + "设备台账导出模板.xlsx";
        EasyExcel.write(response.getOutputStream(), DssDeviceInformationDTO.class)
                .registerWriteHandler(new CustomSheetWriteHandler(dictList, page.getTotalCount())) //加下拉框的拦截器
               // .withTemplate(templateFileName)
                .sheet("设备台账")
                .doWrite(page.getList());
//       .doFill(page.getList());

    }


    /**
     * 上传Excel文件
     */
    @PostMapping("/upload/excel")
    @RequiresPermissions("dss:deviceInformation:upload")
    public R uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        if (!FilenameUtils.getExtension(file.getOriginalFilename()).matches("xlsx?")) {
            return R.error("仅支持.xlsx文件");
        }
            //查设备编号列表
            MPJLambdaWrapper<DssDeviceInformationEntity> wrapper = new MPJLambdaWrapper<DssDeviceInformationEntity>()
                    .select(DssDeviceInformationEntity::getId)
                    .select(DssDeviceInformationEntity::getDeviceId);
            List<DssDeviceInformationEntity> dssDeviceInformationEntityList = dssDeviceInformationDao.selectList(wrapper );
            List<String> deviceIdList=new ArrayList<>();
            for (DssDeviceInformationEntity dssDeviceInformationEntity : dssDeviceInformationEntityList) {
                deviceIdList.add(dssDeviceInformationEntity.getDeviceId());
            }


            //创建监听器
            ExcelImportListener listener = new ExcelImportListener(dssOperationStatusService,dssDeviceInformationService,deviceIdList,dssDeviceInformationDao);
            try {
            //读取Excel文件
            EasyExcel.read(file.getInputStream(), DssDeviceInformationDTO.class, listener).sheet().doRead();
            if (listener.getSuccessCount()>0&&listener.getErrorCount()!=0){
                return R.ok().put("code", 0)
                        .put("msg", "成功录入"+listener.getSuccessCount()+"条信息，有"+listener.getErrorCount()+"条设备信息已存在");
//                        .put("open",listener.getSuccessCount());
            }else if (listener.getSuccessCount()>0&&listener.getErrorCount()==0){
                return R.ok().put("code", 0)
                        .put("msg", "成功录入"+listener.getSuccessCount()+"条信息");
//                        .put("open",listener.getSuccessCount());
            }
            else {
                return R.ok().put("code", 300)
                        .put("msg", "上传文档中的设备信息都已经存在！");
            }

        }catch (Exception e){
            return R.ok().put("code",400).put("msg",listener.getErrorNull());
        }
    }

    /**
     * @param file     文件
     * @param
     * @Description 上传文件
     */
    @PostMapping("/upload/video")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {

        // 避免文件覆盖--通过UUID修改图片的唯一标识码 -- 名称SDW
        String originalFilename = file.getOriginalFilename();
        //生成一段不重复的字符
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));   // 截取文件名的后缀
        minioUtils.upload(file, fileName);

        // 生成访问URL,GET方法，有效期7天
        String url = minioUtils.getPolicyUrl(fileName, Method.GET, 7, TimeUnit.DAYS);

        return AjaxResult.success(url);
    }


}
